package cn.byapps.hw.service.impl;

import cn.byapps.hw.dao.CourseDao;
import cn.byapps.hw.entity.Clazz;
import cn.byapps.hw.entity.Course;
import cn.byapps.hw.entity.SerialPK;
import cn.byapps.hw.entity.Teacher;
import cn.byapps.hw.service.CourseServcie;
import cn.byapps.hw.service.SerialPKService;
import cn.byapps.hw.vo.CourseVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Transactional
public class CourseServiceImpl implements CourseServcie {

    @Resource
    private CourseDao courseDao;
    @Resource
    private SerialPKService serialPKService;

    @Override
    public List<CourseVO> findVO(Integer pos, Integer rows) {
        int pageNumber = (pos + rows - 1) / rows;
        Pageable pageable = PageRequest.of(pageNumber, rows);
        Page<Course> page = courseDao.findAll(pageable);
        List<Course> courses = page.getContent();
        List<CourseVO> courseVOs = new ArrayList<CourseVO>();
        for (Course c : courses) {
            Set<Clazz> clazzs = serialPKService.getCourse(c).stream().map(SerialPK::getClazz).collect(Collectors.toSet());
            Set<Teacher> teachers = serialPKService.getCourse(c).stream().map(SerialPK::getTeacher).collect(Collectors.toSet());
            CourseVO cVo = new CourseVO(c.getId(), c.getName(), clazzs, teachers);
            courseVOs.add(cVo);
        }
        return courseVOs;
    }

    @Override
    public int count() {
        return (int) courseDao.count();
    }

    @Override
    public void add(Course course) {
        courseDao.save(course);
    }

    @Override
    public void update(Course course) {
        courseDao.save(course);
    }

    @Override
    public void delete(Integer id) {
        List<SerialPK> serialPKS = serialPKService.getCourse(new Course(id, null));
        for (SerialPK serialPK : serialPKS) {
            serialPK.setCourse(null);
            serialPK.setTeacher(null);
        }
        courseDao.deleteById(id);
    }

    @Override
    public List<CourseVO> findVO() {
        List<Course> courses = courseDao.findAll();
        List<CourseVO> courseVOS = new ArrayList<>();
        for (Course course : courses) {
            courseVOS.add(new CourseVO(course.getId(), course.getName(), null, null));
        }
        return courseVOS;
    }
}
